<?php
/**
 * Created by PhpStorm.
 * User: win10
 * Date: 2017/12/18
 * Time: 10:37
 */

namespace common\services;

require __DIR__ . '/qiniu/autoload.php';

use Yii;
use common\services\Qiniu;
use Qiniu\Storage\UploadManager;

class HttpUploadService
{

    /**
     * 七牛上传图片调用方法
     * @param $filePath // 文件名
     * @return bool|string      // 返回url
     */
    public static function qiNiuPictureUpload($filePath)
    {
        if (empty($filePath)) {
            return false;
        }
        $objAuth = new Qiniu();
        $result = $objAuth->uploadFile($filePath);
        if (empty($result) || !is_array($result)) {
            return false;
        }
        $url = 'http://' . $objAuth->domain . '/' . $result['key'];
        return $url;
    }

    /**
     * 七牛url上传图片调用方法
     * @param $url
     * @return bool|string
     */
    public static function qiNiuUrlUpload($url)
    {
        if (empty($url)) {
            return false;
        }
        $objAuth = new Qiniu();
        $result = $objAuth->uploadByUrl($url);
        if (empty($result) || !is_array($result)) {
            return false;
        }
        $url = 'http://' . $objAuth->domain . '/' . $result['key'];
        return $url;
    }

    /**
     * base64位上传图片
     * @param $key
     * @param $filePath
     * @return bool
     */
    public static function qiNiuBase64PictureUpload($key, $filePath)
    {
        if (empty($filePath)) {
            return false;
        }
        $objAuth = new Qiniu();
        $token = $objAuth->uploadToken($objAuth->bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            return 'http://' . $objAuth->domain . '/' . $ret['key'];
        }
    }

    /**
     * CURL
     * @param $url
     * @return mixed
     */
    public static function curlRequest($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $SSL = substr($url, 0, 8) == "https://" ? true : false;
        if ($SSL) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
        }
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }
}